#pragma warning( disable: 4127 4800 4702 )
#include <string>
#include <vector>
#include <windows.h>
#include <commctrl.h>
#include <regstr.h>
#include <stdlib.h>
#include <tchar.h>
typedef std::basic_string<TCHAR> tstring;
using namespace std;

#include "SApp.h"
#include "CViewD3D9.h"
#include "crc32.h"

SApp g_oAppInst; 

//----------------------------------------------
LRESULT CALLBACK SaverWndProc(HWND hWnd,UINT uiMsg,WPARAM wParam,LPARAM lParam)
{
	CView *pView;
	CViewDesc *pViewDesc; HWND hMain;
	int iId;
	if (uiMsg == WM_CREATE)
	{
		CREATESTRUCT *cs = (CREATESTRUCT*)lParam;
		pViewDesc = static_cast<CViewDesc*>( cs->lpCreateParams );
		SetWindowLong(hWnd, 0, pViewDesc->id);
		pView = new CViewD3D9(hWnd, *pViewDesc);
		SetWindowLong(hWnd, GWL_USERDATA, (LONG)pView);
		SApp::instance()->addView(pView);
		iId = pViewDesc->id;
	}
	else
	{
		pView = (CViewD3D9*)GetWindowLong(hWnd, GWL_USERDATA);
		iId = GetWindowLong(hWnd, 0);
	}
	if (iId <= 0)
		hMain = hWnd;
	else
		hMain = SApp::instance()->m_oViews[0]->m_hWnd;

	SApp::instance()->processMessage(uiMsg, iId, wParam, lParam);

	return DefWindowProc(hWnd, uiMsg, wParam, lParam);
}

//----------------------------------------------
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE,LPSTR,int)
{
	initCrc32();

	SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_IDLE );

	INITCOMMONCONTROLSEX icx;
	ZeroMemory(&icx, sizeof(icx));
	icx.dwSize	= sizeof(icx);
	icx.dwICC	= ICC_UPDOWN_CLASS;
	InitCommonControlsEx(&icx);

	WNDCLASS wc;
	ZeroMemory(&wc, sizeof(wc));

	wc.lpfnWndProc		= SaverWndProc;
	wc.cbWndExtra		= 8;
	wc.style			= CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
	wc.lpszClassName	= _T("ScrClass");
	RegisterClass(&wc);

	SApp::setInstance(new SApp);
	SApp::instance()->init(hInst);
	SApp::instance()->run();

	return 0;
}
